package com.bjpowernode.service.impl;

import com.alibaba.excel.EasyExcel;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TClue;
import com.bjpowernode.entity.TCustomer;
import com.bjpowernode.entity.TCustomerDO;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.mapper.TClueMapper;
import com.bjpowernode.mapper.TCustomerMapper;
import com.bjpowernode.query.BaseQuery;
import com.bjpowernode.query.CustomerQuery;
import com.bjpowernode.service.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private TCustomerMapper tCustomerMapper;

    @Resource
    private TClueMapper tClueMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean convertCustomer(CustomerQuery customerQuery) {
        //1、验证一下该线索是否已经转过客户，如果转过了，就不能再转了
        TClue tClue = tClueMapper.selectByState(customerQuery.getClueId());
        if (tClue != null) { //说明该线索已经转过客户了，不能再转了
            throw new RuntimeException("该线索已经转过客户了，不能再转了.");
        }

        //2、转成客户，向客户表插入一条客户数据
        TCustomer tCustomer = new TCustomer();
        BeanUtils.copyProperties(customerQuery, tCustomer);
        //创建时间
        tCustomer.setCreateTime(new Date());
        //创建人
        TUser authUser = (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer currentLoginUserId = authUser.getId();
        tCustomer.setCreateBy(currentLoginUserId);
        int insert = tCustomerMapper.insertSelective(tCustomer);
        if (insert <= 0) {
            throw new RuntimeException("转换客户失败.");
        }

        //3、已经转了客户，需要把该线索的状态改为“已转客户”
        TClue cl = new TClue();
        cl.setId(customerQuery.getClueId());
        cl.setState(-1); //-1表示“已转客户”
        int update = tClueMapper.updateByPrimaryKeySelective(cl);
        if (update <= 0) {
            throw new RuntimeException("转换客户失败.");
        }
        //返回true表示转换成功
        return true;
    }

    @Override
    public PageInfo<TCustomer> getCustomerPage(Integer current) {
        //1.设置PageHelper (第一个参数是查第几页，第二个参数每页查多少条数据)
        PageHelper.startPage(current, Constants.PAGE_SIZE);

        //2.查询数据库表的数据
        List<TCustomer> list = tCustomerMapper.selectCustomerPage(new BaseQuery());

        //3.封装分页数据到PageInfo
        PageInfo<TCustomer> info = new PageInfo<>(list);

        //4.返回PageInfo对象
        return info;
    }

    @Override
    public TCustomer getCustomerById(Integer customerId) {
        return tCustomerMapper.selectById(customerId);
    }

    @Override
    public void exportExcel(OutputStream os, List<String> idList) {
        List<TCustomer> tCustomerList = tCustomerMapper.selectCustomerDetailList(new BaseQuery(), idList);

        List<TCustomerDO> newCustomerList = new ArrayList<>();
        tCustomerList.forEach(tCustomer -> {
            TCustomerDO tCustomerDO = new TCustomerDO();

            tCustomerDO.setId(tCustomer.getId());
            tCustomerDO.setClueId(tCustomer.getClueId());
            tCustomerDO.setOwnerName(ObjectUtils.isEmpty(tCustomer.getOwnerDO()) ? Constants.EMPTY : tCustomer.getOwnerDO().getName());
            tCustomerDO.setActivityName(ObjectUtils.isEmpty(tCustomer.getActivityDO()) ? Constants.EMPTY : tCustomer.getActivityDO().getName());
            tCustomerDO.setFullName(tCustomer.getClueDO().getFullName());
            tCustomerDO.setAppellationName(ObjectUtils.isEmpty(tCustomer.getAppellationDO()) ? Constants.EMPTY : tCustomer.getAppellationDO().getTypeValue());
            tCustomerDO.setPhone(tCustomer.getClueDO().getPhone());
            tCustomerDO.setWeixin(tCustomer.getClueDO().getWeixin());
            tCustomerDO.setQq(tCustomer.getClueDO().getQq());
            tCustomerDO.setEmail(tCustomer.getClueDO().getEmail());
            tCustomerDO.setAge(tCustomer.getClueDO().getAge());
            tCustomerDO.setJob(tCustomer.getClueDO().getJob());
            tCustomerDO.setYearIncome(tCustomer.getClueDO().getYearIncome());
            tCustomerDO.setAddress(tCustomer.getClueDO().getAddress());
            tCustomerDO.setNeedLoanName(ObjectUtils.isEmpty(tCustomer.getNeedLoanDO()) ? Constants.EMPTY : tCustomer.getNeedLoanDO().getTypeValue());
            tCustomerDO.setSourceName(ObjectUtils.isEmpty(tCustomer.getSourceDO()) ? Constants.EMPTY : tCustomer.getSourceDO().getTypeValue());
            tCustomerDO.setIntentionProductName(ObjectUtils.isEmpty(tCustomer.getIntentionProductDO()) ? Constants.EMPTY : tCustomer.getIntentionProductDO().getName());
            tCustomerDO.setDescription(tCustomer.getDescription());
            tCustomerDO.setNextContactTime(tCustomer.getNextContactTime());
            tCustomerDO.setCreateTime(tCustomer.getCreateTime());
            tCustomerDO.setCreateByName(ObjectUtils.isEmpty(tCustomer.getCreateByDO()) ? Constants.EMPTY : tCustomer.getCreateByDO().getName());
            tCustomerDO.setEditTime(tCustomer.getEditTime());
            tCustomerDO.setEditByName(ObjectUtils.isEmpty(tCustomer.getEditByDO()) ? Constants.EMPTY : tCustomer.getEditByDO().getName());

            newCustomerList.add(tCustomerDO);
        });

        //write()方法的第一个参数是写出的目的地
        EasyExcel.write(os, TCustomerDO.class).sheet().doWrite(newCustomerList);
    }
}
